using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using NHibernate;
using NHibernate.SqlTypes;
using NHibernate.UserTypes;
using Sedna.Domain;

namespace Sedna.Core.Persistence
{
    /// <summary>
    /// Hibernate infrastructure class that maps <see cref="Time"/> domain value to a INT database column.
    /// 
    /// This mapping can store and return NULL.
    /// </summary>
    public abstract class TimeType : IUserType
    {
        protected abstract Time CreateObject(int value);
        protected abstract int GetValue(Time time);
        
        public object NullSafeGet(IDataReader rs, string[] names, object owner)
        {
            int index = rs.GetOrdinal(names[0]);
            
            return rs.IsDBNull(index)
                ? null
                : CreateObject(Convert.ToInt32(NHibernateUtil.Int32.Get(rs, names[0])));
        }

        public void NullSafeSet(IDbCommand cmd, object value, int index)
        {
            Time time = value as Time;

            if (time != null)
            {
                NHibernateUtil.Int32.Set(cmd, GetValue(time), index);
            }
            else
            {
                NHibernateUtil.Int32.Set(cmd, DBNull.Value, index);
            }
        }

        public object DeepCopy(object value)
        {
            return value; //Time is immutable
        }

        public SqlType[] SqlTypes
        {
            get { return new SqlType[] { NHibernateUtil.Int32.SqlType }; }
        }

        public Type ReturnedType
        {
            get { return typeof(Time); }
        }

        public bool IsMutable
        {
            get { return false; }
        }

        public new bool Equals(object x, object y)
        {
            return x == null ? y == null : x.Equals(y);
        }

        public object Disassemble(object value)
        {
            return value;
        }

        public object Assemble(object cached, Object owner)
        {
            return cached;
        }

        public object Replace(object original, object target, object owner)
        {
            return original;
        }

        public int GetHashCode(Object x)
        {
            return x.GetHashCode();
        }

    }
}
